import axios from 'axios'
import { Message } from 'element-ui'
import store from '@/store'
import router from '@/router'
import { getToken } from '@/utils/auth'
import qs from 'qs'
import { getSign } from '@/utils/sign'
import { Loading } from 'element-ui'

// axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded'

// create an axios instance
const service = axios.create({
  baseURL: process.env.VUE_APP_API_URL, // api 的 base_url
  transformRequest: [function(data) {
    data = qs.stringify(data)
    return data
  }],
  headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
  withCredentials: true,
  timeout: 90000 // request timeout
})

function getTimeZone() {
  var i = new Date().getTimezoneOffset() / 60
  i = -i
  if (i > 0) {
    return '+' + i
  } else if (i === 0) {
    return ''
  } else {
    return i
  }
}

// request interceptor
service.interceptors.request.use(
  config => {
    // Do something before request is sent
    // 添加通用请求参数
    if (config.data && !config.data.skipLoading) {
      const loadingInstance = Loading.service({
        lock: true,
        fullscreen: true,
        background: 'rgba(0, 0, 0, 0.7)'
      })
      config.loadingInstance = loadingInstance
    }
    var requestData = Object.assign({}, config.data)
    requestData.timestamp = new Date().getTime()
    requestData.appkey = process.env.APP_KEY
    requestData.sign = getSign(requestData)
    config.data = requestData
    if (store.getters.token) {
      // 让每个请求携带token-- ['X-Token']为自定义key 请根据实际情况自行修改
      config.headers['sapi-token'] = getToken()
    }
    config.headers['m-time-zone'] = getTimeZone()
    return config
  },
  error => {
    // Do something with request error
    console.log(error) // for debug
    Promise.reject(error)
  }
)

// response interceptor
service.interceptors.response.use(
  response => {
    if (response && response.config && response.config.loadingInstance) {
      response.config.loadingInstance.close()
    }
    if (response.headers['sapi-token']) {
      console.warn('token change')
      store.dispatch('TokenChange', response.headers['sapi-token']).then(() => {
      })
    }
    const res = response.data
    if (res.code === 600) {
      store.dispatch('FedLogOut').then(() => {
        location.reload() // 为了重新实例化vue-router对象 避免bug
      })
      return Promise.reject('error')
    }
    if (res.code === 403) {
      Message.error('权限不足')
      return Promise.reject('error')
    }
    return response
  },
  error => {
    if (error && error.config && error.config.loadingInstance) {
      error.config.loadingInstance.close()
    }
    if (!error.response) {
      Message.error(error.message)
    }
    const status = error.response.status
    if (status === 403 || status === 401) {
      router.push('/401')
    } else if (status === 404) {
      router.push('/404')
    } else {
      Message.error(error.message)
    }

    return Promise.reject(error)
  }
)

export default service
